package com.xp.gather2.comment.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * cookie工具类
 * @author chenz
 * @date Aug 22, 2012 7:43:34 PM
 * @filename CookieUtil.java
 */
public class CookieUtil {
	private HttpServletRequest request;
	private HttpServletResponse response;

	public CookieUtil(HttpServletRequest request,HttpServletResponse response){
		this.request = request;
		this.response = response;
	}
	/**
	 * 添加cookie
	 * @param name
	 * @param value
	 */
	public void addCookie(String name,String value,int age){
		Cookie cookie = new Cookie(name,value);
		cookie.setPath("/");
		cookie.setMaxAge(age);
		response.addCookie(cookie);
	}
	/**
	 * 获得cookie对象
	 * @param cookieName
	 * @return
	 */
	public Cookie getCookie(String cookieName){
		Cookie[] cookies = request.getCookies();
		Cookie cookie = null;
        try {
            if (cookies != null && cookies.length > 0) {
                for (int i = 0; i < cookies.length; i++) {
                    cookie = cookies[i];
                    if (cookie.getName().equals(cookieName)) {
                        return cookie;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cookie;
	}
	/**
	 * 获得cookie值
	 * @param cookieName
	 * @return
	 */
    public String getCookieValue(String cookieName) {
        if (cookieName != null) {
            Cookie cookie = getCookie(cookieName);
            if(cookie!=null){
                return cookie.getValue();
            }
        }
        return "";
    }
    /**
     * 删除cookie
     * @param cookieName
     * @return
     */
    public boolean deleteCookie(String cookieName) {
        if (cookieName != null) {
            Cookie cookie = getCookie(cookieName);
            if(cookie!=null){
                cookie.setMaxAge(0);
                cookie.setPath("/");
                response.addCookie(cookie);
                return true;
            }
        }
        return false;
    }
}
